// component/tabview/index.js
const windowWidth = wx.getSystemInfoSync().windowWidth;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    activeTab:{
      type:Number,
      value:0
    },
    tabTitles:{
      type:Array,
      value: ["页面1", "页面2", "页面3"]
    },
    bodyScrollLeft: {
      type: Number,
      value: 0
    },
    width:{
      type:Number,
      value: windowWidth/3
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
   * 点击tab
  */
    selectTab: function (e) {
      console.log(e);
      //设置选中样式
      let toIndex = e.currentTarget.dataset.index;
      let fromIndex = this.properties.activeTab;
      if (toIndex === fromIndex) {
        return;
      }
      let offSetLeft = e.currentTarget.offsetLeft;
      this.scrollTopBar(offSetLeft, toIndex);
      this.updatePage(fromIndex, toIndex);
    },
    /**
     * 更新展示页面及选中样式
     */
    updatePage: function (fromIndex, toIndex) {
      // body
      let bodyScrollLeft = toIndex * windowWidth;
      this.setData({
        activeTab: toIndex,
        bodyScrollLeft: bodyScrollLeft,
      });
    },
    /**
     * 自适应tabBar选中位置
     */
    scrollTopBar: function (offSetLeft, index) {
      let that = this;
      var nodeId = "#item-" + index;
      wx.createSelectorQuery().select(nodeId).boundingClientRect(function (rect) {
        console.log(rect)
        var res = wx.getSystemInfoSync();
        console.log(res)
        let targetOffSetLeft = offSetLeft - (res.windowWidth / 2) + (73 / 2);
        that.setData({
          scrollLeft: targetOffSetLeft
        });
      }).exec();
    },
    /**
     * 滑动停止
     */
    scrollEnded: function (e) {
      let that = this;
      wx.createSelectorQuery().select('#scroll-view-bodyId').fields({
        dataset: true,
        size: true,
        scrollOffset: true,
        properties: ['scrollX', 'scrollY']
      }, function (res) {
        console.log(res)
        let endIndex = Math.round(res.scrollLeft / windowWidth);
        that.updatePage(that.activeTab, endIndex);
        wx.createSelectorQuery().selectAll('.scroll-header-item-wraper').boundingClientRect(function (rects) {
          var offsetLeft = 0;
          for (var i = 0; i < endIndex; i++) {
            offsetLeft += rects[i].width;
          }
          console.log(offsetLeft);
          that.scrollTopBar(offsetLeft, endIndex);
        }).exec();
      }).exec();
    }
  }
})
